#include"CCStreamServer.h"

bool CCStreamServer::m_isExit = false;

CCStreamServer::CCStreamServer()
{
    printf("构造函数\n");
    m_listenSocketfd = -1;
}
CCStreamServer::~CCStreamServer()
{

}

void CCStreamServer::closeSockfd(){

    if(m_listenSocketfd){
        closeSockfd();
        return;
    }

}
void CCStreamServer::xExit(){
    printf("xExit\n");
    m_isExit = true;
}
void CCStreamServer::StartTCPServer(){
    m_listenSocketfd = socket(AF_INET,SOCK_STREAM,0);
    if(m_listenSocketfd<0){
        printf("socket filed..");
        closeSockfd();
        m_listenSocketfd = -1;
        return;
    }

    int opt = 1;
    int len = sizeof(int);
    if(setsockopt(m_listenSocketfd,SOL_SOCKET,SO_REUSEADDR,&opt,len)<0){
        printf("setsockopt filed..");
        closeSockfd();
        m_listenSocketfd = -1;
        return;
    }

    fcntl(m_listenSocketfd,F_SETFL,O_NONBLOCK);

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(LISTEN_POT);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    int ret = bind(m_listenSocketfd,(struct sockaddr *)&server_addr,sizeof(server_addr));
    if(ret<0){
        printf("bind filed..");
        closeSockfd();
        return ;
    }

    ret = listen(m_listenSocketfd,10);

    if(ret<0){
        printf("listen filed..");
        closeSockfd();
        return ;
    }
    
    printf("SUCCESS AND LISTENING...\n");
    while(!m_isExit){
        struct sockaddr_in client_addr;
        bzero(&client_addr,sizeof(client_addr));
        socklen_t size = sizeof(struct sockaddr);
        int socketfd = accept(m_listenSocketfd,(struct sockaddr*)&client_addr,&size);
        if(socketfd>0){
            printf("\n------------------------ACCPET NEW CONNECT--------------------------\n");
            printf("connected socket %d,ip address: %s\n",socketfd,inet_ntoa(client_addr.sin_addr));
            
            CCClientProcess* clientProcess = new CCClientProcess();
            clientProcess->StartClientProcessWithSockfd(socketfd);
            m_clientsProcess.push_back(clientProcess);
        }
        //std::cout<<"Vector Client has num: "<<m_clientsProcess.size()<<std::endl;
        usleep(2000*1000);
    }




}

void CCStreamServer::checkClientAlive(){
    if(m_clientsProcess.size()<=0){
        return;
    }

    for(auto it = m_clientsProcess.begin();it!=m_clientsProcess.end();){
        auto client = *it;
        if(client->getClientAliveStatus()==false){
            m_clientsProcess.erase(it);
            delete client;
        }else{
            it++;
        }
    }
}

void CCStreamServer::SendAVStream(uint8_t* buff,uint32_t len,uint16_t type){
    checkClientAlive();

    for(int i=0;i<m_clientsProcess.size();i++){
        CCClientProcess* clienPtr = (CCClientProcess*)m_clientsProcess[i];
        if(clienPtr!=NULL){
            clienPtr->EnqueueAVStream(buff,len,type);
            printf("encoder length:%d\n",len);
        }
    }
}